﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;

namespace AbpDemo.UploadFiles
{
    [Authorize]
    [ApiExplorerSettings(GroupName = "v1")]
    public class UploadFile : ApplicationService, IApplicationService
    {
        private readonly IWebHostEnvironment environment;

        public UploadFile(IWebHostEnvironment environment)
        {
            this.environment = environment;
        }

        [HttpPost("/UploadFile")]
        public async Task<ResultDto<string>> Upload(IFormFile form)
        {
            var path = $"/UploadFile/Images/{DateTime.Now.ToString("yyyyMMdd")}/";
            if (!Directory.Exists($"{environment.WebRootPath}{path}"))
            {
                Directory.CreateDirectory($"{environment.WebRootPath}{path}");
            }

            var ext = Path.GetExtension(form.FileName);

            var fileName = $"{path}{DateTime.Now.ToString("yyyyMMddHHmmss")}{ext}";

            using (FileStream file = new FileStream($"{environment.WebRootPath}{fileName}", FileMode.Create))
            {
                await form.CopyToAsync(file);
            }

            return new ResultDto<string> { Code = ResultState.Success, Data = fileName };
        }
    }
}
